package com.lan3g.Test.view;

import com.lan3g.Test.controller.LoginController;
import com.lan3g.Test.pojo.User;
import com.lan3g.Test.util.MD5Util;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Set;

@WebServlet(name = "LoginServlet",urlPatterns = "/login.jsp")
public class LoginServlet extends HttpServlet {
    private LoginController loginController
            = new LoginController();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        password = MD5Util.MD5WithSalt(password);

        User user =loginController.login(username,password);

        if (user == null) {
            // 登录失败
            fieldMsg(request, response,
                    "用户名/密码错误,点击返回登录页面");
        } else {
            // 登录成功


            // 登录成功 把这个用户名 添加到loginUsers中
            ServletContext app = getServletContext();
            Set<String> loginUsers =
                    (Set<String>) app.getAttribute("loginUsers");
            loginUsers.add(username);

            response.sendRedirect("/index.jsp");
        }

    }

    private void fieldMsg(HttpServletRequest request,
                          HttpServletResponse response,
                          String msg) throws ServletException, IOException {
        // String msg = "用户名/密码错误,点击返回登录页面";
        String path = "/login.jsp";
        request.setAttribute("msg", msg);
        request.setAttribute("path", path);
        response.setStatus(302);
        response.setHeader("Refresh", ";URL=/index.jsp");
        request.getRequestDispatcher("/Exam/msg.jsp")
                .forward(request, response);
    }



    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request,response);

    }
}
